package cn.zhaoyuening.hadoopdemo.mapper;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class WordCounterMapper extends Mapper<LongWritable,Text,Text,IntWritable> {
    private static final int ONE = 1;

    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        String[] strings = value.toString().split("\\s+");
        Map<String, Integer> map = new HashMap<String, Integer>();
        for (String str :
                strings) {
            if (map.containsKey(str)) {
                map.put(str,map.get(str) + ONE);
            }else{
                map.put(str,ONE);
            }
        }

        for (String str :
                map.keySet()) {
            context.write(new Text(str),new IntWritable(map.get(str)));
        }
    }
}
